package org.wmine.algo;
import org.wmine.core.ProjectManager;
import org.wmine.core.CSVReader;
import org.wmine.core.MainWindow;
import org.wmine.core.BasicTabPanel;
import org.wmine.core.WMineConstants;
import org.wmine.data.Attribute;
import org.wmine.data.DataSet;
import org.wmine.data.InvalidCursorPositionException;
import org.wmine.data.Table;
import org.wmine.data.TableResultSet;
import org.wmine.data.XMLDataReader;
import org.xml.sax.SAXException;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JButton;
import java.awt.event.*;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.StringBufferInputStream;
import java.util.Iterator;
import javax.swing.border.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.xml.parsers.ParserConfigurationException;


public class AlgorithmPanel extends BasicTabPanel{
	JTable tableData;
	JTabbedPane pan3;
	String filename;
	JScrollPane scrollPane;	
	DefaultTableModel dtm;
	String AlgoLabel;
	String dataValues[][]=null;
	String[] columnNames=null;
	Object [] items={"Missing Values","Discretization"};
	int cntRow,cntCol;
	String tablename;
	Iterator itrAttr;
	
	public String getTitle() {
		return "Mining Algorithms";
	}

	public String getTooltip() {
		return "Apply the mining algorithms on the preprocessed data";
	}

	public JPanel buildWindow() {
		final JPanel mainPanel=new JPanel();
		mainPanel.setSize(750,700);
		mainPanel.setLayout(null);
		
			//final JPanel pan3=new JPanel();
			//final JTabbedPane pan3=new JTabbedPane();
		 pan3=new JTabbedPane();
			//pan3.setLayout(null);
			pan3.setBounds(245,10,450,460);
			
			JPanel pan1=new JPanel();
			pan1.setLayout(null);
			pan1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Input"));
			pan1.setBounds(10,10,230,250);
		
				final JButton but1=new JButton("Process");
				final JButton but2=new JButton("Save");
				JLabel lab1=new JLabel("Select the file:");
				lab1.setBounds(10,10,160,30);
				JComboBox com1=new JComboBox();
				com1.addItem(new String(" --select-- "));
				if(ProjectManager.getUniqueInstance().isProjectOpened())
				{	String []list=ProjectManager.getUniqueInstance().getFileNamesArray("preprocess");
					for(int i=0;i<list.length;i++)
						com1.addItem(list[i]);
				}
				
				//com1.addItem(new String("PreProcessed.xml"));
				//com1.addItem(new String("PreProcessed1.xml"));
				//com1.addItem(new String("PreProcessed2.xml"));
				//com1.addItem(new String("PreProcessed3.xml"));
				
				com1.setEditable(false);
				com1.setBounds(10,45,160,20);	
				com1.addItemListener(new ItemListener() {
				     public void itemStateChanged(ItemEvent e)
				     {
				     	MainWindow.getInstance().showOnStatusBar(e.getItem().toString());
				     	String fn=e.getItem().toString();
				     	String label="Data From File '"+e.getItem().toString()+"':";
				     //	pan3.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),label));
				        try
					 		{
				        	String fl="C:\\"+fn;
				        	//System.out.println(fl);
					 		LoadData(fn);
					 		//LoadData("C:\\PreProcessed.xml");
					 		}catch(Exception ee){System.out.println(ee);}
					 		
					 		dtm=new DefaultTableModel(dataValues,columnNames);
					 		tableData = new JTable(dtm);
					 		tableData.setEnabled(false);
					 		dtm.addTableModelListener(new TableModelListener()
					 		{
					 			public void tableChanged(TableModelEvent tme)
					 			{
						 			System.out.println("table changed");
						 					System.out.println(dtm.getDataVector());
						 			
					 			}
					 		});
			 		
						 		
					 		scrollPane=new JScrollPane(tableData);
					 		scrollPane.setBounds(10,30,420,410);
					 		//scrollPane.
					 		if(pan3!=null)
					 			pan3.removeAll();
					 		pan3.add(scrollPane);
					 		pan3.setTitleAt(0,"Input Data");
					 		//mainPanel.add(pan3);
				     
				     }});
				pan1.add(lab1);
				pan1.add(com1);	
				
				JLabel lab2=new JLabel("Select the mining technique:");
				lab2.setBounds(10,70,230,30);
				
				JComboBox com2=new JComboBox();
				com2.addItem(new String(" --select-- "));
				com2.addItem(new String("Statistical Analysis"));
				com2.addItem(new String("Frequency Distribution"));
				com2.addItem(new String("Linear Regression"));
				com2.addItem(new String("Decision Tree"));
				com2.addItem(new String("Bayesian Method"));
				com2.addItem(new String("Rule Based Induction"));
				com2.addItem(new String("Clustering by k-means"));
				com2.addItem(new String("Association Analysis"));
				com2.setEditable(false);
				com2.setBounds(10,105,160,20);

				pan1.add(lab2);
				pan1.add(com2);
		
				but1.setBounds(10,140,85,30);
				but2.setBounds(100,140,80,30);
				///start of but1
				but1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent ae)
				{	
					if(AlgoLabel.equals("Frequency Distribution"))
					{
						FreqDistri sd=new FreqDistri(columnNames,cntCol);
						sd.setBounds(300,200,300,300);
						sd.setVisible(true);
					}	
					if(AlgoLabel.equals("Bayesian Method"))
					{
						Naive sd=new Naive(columnNames,cntCol,cntRow,dataValues);
						sd.setVisible(true);
					}
					if(AlgoLabel.equals("Decision Tree"))
					{
						//DT1 sd=new 
						getDT1(columnNames,cntCol,cntRow,dataValues);
						//sd.setVisible(true);
					}
					if(AlgoLabel.equals("Rule Based Induction"))
					{
						//ruleBased rb=new ruleBased(attribs1,colknt1,cntRow1,data2,selected,classLbl);
						getRules(columnNames,cntCol,cntRow,dataValues);
					}
					if(AlgoLabel.equals("Statistical Analysis"))
					{
						Stats sd=new Stats(columnNames,cntCol);
						sd.setBounds(300,200,300,300);
						sd.setVisible(true);
					}
					if(AlgoLabel.equals("Linear Regression"))
					{
						regression sd=new regression(columnNames,cntCol);
						sd.setBounds(300,200,300,300);
						sd.setVisible(true);
					}	
					if(AlgoLabel.equals("Clustering by k-means"))
					{
						clusteringLast sd=new clusteringLast(columnNames,cntCol,cntRow,dataValues);
						//sd.setBounds(350,300,310,180);
						sd.setVisible(true);
					}	
					if(AlgoLabel.equals("Association Analysis"))
					{
						System.out.println("Going");
						FPTree sd=new FPTree(columnNames,cntCol,cntRow,dataValues);
					//	sd.setBounds(300,200,300,300);
						System.out.println("Going2");
						sd.setVisible(true);
						System.out.println("Going3");
					}	
				}});
				///////////end of but1
				pan1.add(but1);
				pan1.add(but2);
		
			final JPanel pan2=new JPanel();
			pan2.setLayout(null);
			pan2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Description"));
			final JLabel descri1=new JLabel();
			descri1.setText("<html><body>Description of the algorithm" +
                                "</body></html>");
			descri1.setBounds(30,30,170,170);
			pan2.setBounds(10,260,230,210);
			pan2.add(descri1);
		
			mainPanel.add(pan2);
		
			com2.addItemListener(new ItemListener() {
		     public void itemStateChanged(ItemEvent e)
		     {
		    	 if(pan3.getTabCount()==2)
			 			pan3.remove(1);
		     	AlgoLabel=e.getItem().toString();
		        pan2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),AlgoLabel));	
		        if(AlgoLabel.equals("Frequency Distribution"))
		        {
		        		descri1.setText("<html><body> This Method Finds out Frequency of Presence of Values in Data Based Upon Specified Number of Intervals" +
                  "</body></html>");
		        }
		        else
		        	if(AlgoLabel.equals("Statistical Analysis"))
			        {
			        		descri1.setText("<html><body> This Method Finds out Mean, Mode, Median, Standard deviation of the specified variables and also finds out the Correlation between two variables" +
	                  "</body></html>");
			        }
		        	else
		        		if(AlgoLabel.equals("Linear Regression"))
				        {
				    descri1.setText("<html><body>It involves a response variable,y,and a single predictor variable,x.It models y as a linear function of x i.e.<p> <b> y=b+wx</b> where b and w are regression coefficients " +
		                  "</body></html>");
				        }
		        		else
			        		if(AlgoLabel.equals("Rule Based Induction"))
					        {
					    descri1.setText("<html><body>In this, a model is learned and is represented as a set of IF THEN rules!Its a classification technique." +
			                  "</body></html>");
					        }
			        		else
				        		if(AlgoLabel.equals("Decision Tree"))
						        {
						    descri1.setText("<html><body>It is the learning of decision trees from class labeled training tuples using ID3 Algorithm. Its a classification technique." +
				                  "</body></html>");
						        }
				        		else
					       	if(AlgoLabel.equals("Bayesian Method"))
							{
							    descri1.setText("<html><body>It is a logical regression and uses a logistic curve.The logistic curve gives a value between 0 and 1 so it can be interpreted as the probability of class membership" +
					                  "</body></html>");
							}
					       	else
					       	if(AlgoLabel.equals("Clustering by k-means"))
							{
								    descri1.setText("<html><body>It forms different clusters by grouping the data into classes.It can be used on unclassified data.K-means technique is used here to form the clusters" +
						                  "</body></html>");
							}
					       	else
					       	if(AlgoLabel.equals("Association Analysis"))
							{
									    descri1.setText("<html><body>" +
									    		"It is concerned with finding patterns such as itemsets, that appear in a data set frequently"+
							                  "</body></html>");
							}
		        but1.setEnabled(true);
		       		        
		     }
			});
		
		mainPanel.add(pan1);		
    	mainPanel.add(pan3);
		return mainPanel;
	}		
	public void ActionPerformed(ActionEvent ae)
	{
		System.out.println(ae.getActionCommand());	
	}
	void LoadData(String fname) throws ParserConfigurationException, SAXException, IOException
	{
		
		DataSet dataSet = new DataSet();
		dataSet.reset();
		String filename1=fname; // have to append initial path not done yet
		if(filename1.endsWith(".xml"))
		{
			filename1=fname;
			dataSet.setDataReader(new XMLDataReader(new StringBufferInputStream(ProjectManager.getUniqueInstance().readFile(fname))));
			tablename=dataSet.getTableName();
		}
		System.out.println("data loaded");
		cntCol=dataSet.getAttributeCount();
		cntRow=dataSet.getTupleCount();
		System.out.println(cntCol+ " " +cntRow);
		
		columnNames=new String[cntCol];
		Iterator<Attribute> colnames= dataSet.getAttributeIterator();
		itrAttr=colnames;
		int i=0;
		
		while(colnames.hasNext())
		{
			Attribute s=colnames.next();
			System.out.println("s:"+s.getAttributeName());
			
			columnNames[i++]=s.getAttributeName();
		}
		/*
		Table table=new Table();
		String tablename=table.getNameTable();
		System.out.println("tablename: "+tablename);*/
		TableResultSet resultSet = dataSet.getTableResultSet();

		// creating memory for dataValues
		dataValues=new String[cntRow][cntCol];
	 	int j=0;
		while(resultSet.hasNext()) 
		{
			try 
			{			
				for(i=0;i<cntCol;i++)
				{
					if(resultSet.getString(i).equals("null"))
						dataValues[j][i]="?";
					else
						dataValues[j][i]=resultSet.getString(i);
					System.out.println("Tuple :"+ resultSet.getString(i));					
				}
			}catch (InvalidCursorPositionException e) 
			{
				e.printStackTrace();
			}
			j++;
			//in first attribute
			//System.out.println("Value"+dataValues[j-1][1]);
		}
		for(int jj=0;jj<cntCol;jj++)
		{
			System.out.print(columnNames[jj]+" ");			
		}
		System.out.println("\n"+j+"no.of tuples will be there ");
		for(int ii=0;ii<j;ii++)
		for(int jj=0;jj<cntCol;jj++)
		{
			System.out.println("("+(ii+1)+","+(jj+1)+") =>" +dataValues[ii][jj]);
		}
		resultSet.reset();
		dataSet.reset();
		
	}
//}
//////////////

/////////////////////////////////

/////////////////////////////



///////////////

//class DT1 extends JFrame
//{
	String [] attribs1;int [] checkCnt;
	String classLbl;JCheckBox [] cb111;
	int colknt1,cntRow1;int i;String Goalitem;
	String [][]data2;int [] selected;
	public void getDT1(final String[]attribs,final int colknt,final int cntRow,final String [][] data)
	{
		attribs1=attribs;colknt1=colknt;cntRow1=cntRow;	data2=data;
		//final Container c=this.getContentPane();
		final JFrame frame=new JFrame();
		frame.setTitle("Select the Attributes");
		JPanel mainPanel=new JPanel();
		mainPanel.setLayout(new GridLayout(colknt+6,1));
		mainPanel.add(new JLabel("Class Label Attribute:"));
		final JComboBox cb=new JComboBox();
		for(int j = 0;j<colknt;j++)	{cb.addItem(attribs[j]);}
		cb.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e){classLbl=e.getItem().toString();}});
		mainPanel.add(cb);
		
		mainPanel.add(new JLabel(""));mainPanel.add(new JLabel("Select the Attributes:"));
		cb111=new JCheckBox[colknt];checkCnt=new int[colknt];
		ActionListener listener=new ActionListener(){public void actionPerformed(ActionEvent ae){update();}};
		for(i = 0;i<colknt;i++)
		{
			cb111[i]=new JCheckBox(attribs[i]);
			cb111[i].addActionListener(listener);
			mainPanel.add(cb111[i]);
		}
		mainPanel.add(new JLabel(""));
		JButton but1=new JButton("OK");
		//but1.setBounds(10,45,110,20);
		mainPanel.add(but1);
		but1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent ae)
		{
			//this.dispose();
			frame.dispose();
			selected=new int[cb111.length];
			Goalitem=(String) cb.getSelectedItem();
			for(int s=0;s<cb111.length;s++)		{get(s);}
			JPanel jp=(new DT()).getDT(attribs1,colknt1,cntRow1,data2,selected,classLbl);
			//if(jp==null) System.out.print("leave it");
			jp.setBounds(10,30,4200,410);
			//else 
				pan3.add(jp);
				//pan3.setTabPlacement(JTabbedPane.TOP);
				pan3.setTitleAt(1,"Decision Tree");
		}});
		frame.add(mainPanel);
		frame.setBounds(300,200,300,(32*(colknt+1)));
		frame.setVisible(true);
	}
	void get(int i)
	{
		if(Goalitem.equals(attribs1[i]))
		{//System.out.print(Goalitem);
			selected[i]=2;}
		else if(cb111[i].isSelected())
		{
			//System.out.print("ok");
			selected[i]=1;
		}
		else
			selected[i]=0;
		
		
	}
	void callDT()
	{
		//new DT1(attribs1,colknt1,cntRow1,data2,selected,classLbl);
	}
	void update()
	{
		//	checkCnt[i]++;
	}
	public static void main(String [] args)
	{
		
	}
	public void getRules(final String[]attribs,final int colknt,final int cntRow,final String [][] data)
	{
	attribs1=attribs;colknt1=colknt;cntRow1=cntRow;	data2=data;
	//final Container c=this.getContentPane();
	final JFrame frame=new JFrame();
	frame.setTitle("Select the Attributes");
	JPanel mainPanel=new JPanel();
	mainPanel.setLayout(new GridLayout(colknt+6,1));
	mainPanel.add(new JLabel("Class Label Attribute:"));
	final JComboBox cb=new JComboBox();
	for(int j = 0;j<colknt;j++)	{cb.addItem(attribs[j]);}
	cb.addItemListener(new ItemListener() {
		public void itemStateChanged(ItemEvent e){classLbl=e.getItem().toString();}});
	mainPanel.add(cb);
	
	mainPanel.add(new JLabel(""));mainPanel.add(new JLabel("Select the Attributes:"));
	cb111=new JCheckBox[colknt];checkCnt=new int[colknt];
	ActionListener listener=new ActionListener(){public void actionPerformed(ActionEvent ae){update();}};
	for(i = 0;i<colknt;i++)
	{
		cb111[i]=new JCheckBox(attribs[i]);
		cb111[i].addActionListener(listener);
		mainPanel.add(cb111[i]);
	}
	mainPanel.add(new JLabel(""));
	JButton but1=new JButton("OK");
	//but1.setBounds(10,45,110,20);
	mainPanel.add(but1);
	but1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent ae)
	{
		//this.dispose();
		frame.dispose();
		selected=new int[cb111.length];
		Goalitem=(String) cb.getSelectedItem();
		for(int s=0;s<cb111.length;s++)		{get(s);}
		//JPanel jp=(new DT()).getDT(attribs1,colknt1,cntRow1,data2,selected,classLbl);
		new ruleBased(attribs1,colknt1,cntRow1,data2,selected,classLbl);
		//if(jp==null) System.out.print("leave it");
		//jp.setBounds(10,30,4200,410);
		//else 
			//pan3.add(jp);
			//pan3.setTabPlacement(JTabbedPane.TOP);
			//pan3.setTitleAt(1,"Decision Tree");
	}});
	frame.add(mainPanel);
	frame.setBounds(300,200,300,(32*(colknt+1)));
	frame.setVisible(true);

}          
}
   




